package com.egg.ylt.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.egg.ylt.R;
import com.egg.ylt.Utils.API;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.DateUtils;
import com.egg.ylt.Utils.UtilDynamicWidth;
import com.egg.ylt.activity.ACT_GrowthStamp;
import com.egg.ylt.activity.ACT_PhoneInvite;
import com.egg.ylt.activity.ACT_SwitchBaby;
import com.egg.ylt.activity.ACT_WriteAndChosePhotos;
import com.egg.ylt.adapter.ADA_SelectRelation;
import com.egg.ylt.adapter.record.ADA_BabyDynamicMsgList;
import com.egg.ylt.pojo.BabyDynamicMsgEntity;
import com.egg.ylt.pojo.CurrentBabyInfoEntity;
import com.egg.ylt.pojo.RelationEntity;
import com.egg.ylt.pojo.UploadPhotoEntity;
import com.egg.ylt.presenter.impl.RecordPresenter;
import com.egg.ylt.uploadingphoto.UriUtils;
import com.egg.ylt.view.IRecordView;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.ruffian.library.widget.RImageView;
import com.ruffian.library.widget.RTextView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMWeb;
import com.yonyou.framework.library.adapter.rv.MultiItemTypeAdapter;
import com.yonyou.framework.library.base.BaseFragment;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.CommonUtils;
import com.yonyou.framework.library.common.utils.AppSharedPreferences;
import com.yonyou.framework.library.common.utils.DisplayUtil;
import com.yonyou.framework.library.common.utils.ScreenUtil;
import com.yonyou.framework.library.dialog.AlertDialog;
import com.yonyou.framework.library.eventbus.EventCenter;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created By Dlx
 * on 2019/1/17
 */
public class FRA_Record extends BaseFragment<RecordPresenter> implements IRecordView, XRecyclerView.LoadingListener {
    private static final String TAG = "FRA_Record";
    // 拍照回传码
    public final static int CAMERA_REQUEST_CODE = 0;
    // 相册选择回传吗
    public final static int GALLERY_REQUEST_CODE = 1;
    //系统剪裁
    private final static int GO_TO_ZOOM = 3;
    // 切换宝宝
    private final static int GO_SWITCH_BABY = 4;

    @BindView(R.id.record_title_babylist_iv)
    ImageView babyListIcon;
    @BindView(R.id.myt)
    Toolbar myt;
    @BindView(R.id.record_babyhead_riv)
    RImageView recordBabyheadRiv;
    @BindView(R.id.record_babyname_tv)
    TextView recordBabynameTv;
    @BindView(R.id.record_babybirth_tv)
    TextView recordBabybirthTv;
    @BindView(R.id.record_babyinfo_ll)
    LinearLayout recordBabyinfoLl;
    @BindView(R.id.record_invitehomie_tv)
    RTextView recordInvitehomieTv;
    @BindView(R.id.record_growth_diary_ll)
    LinearLayout recordGrowthDiaryLl;
    @BindView(R.id.record_health_diary_ll)
    LinearLayout recordHealthDiaryLl;
    @BindView(R.id.appointment_appbar)
    AppBarLayout appointmentAppbar;
    @BindView(R.id.baby_dynamic_rv)
    XRecyclerView babyDynamicRv;
    @BindView(R.id.record_floating_camera)
    FloatingActionButton recordFloatingCamera;
    @BindView(R.id.record_floating_photo)
    FloatingActionButton recordFloatingPhoto;
    @BindView(R.id.record_floating_menu)
    FloatingActionMenu recordFloatingMenu;
    Unbinder unbinder;
    @BindView(R.id.record_modify_iv)
    ImageView recordModifyIv;
    @BindView(R.id.record_write_fab)
    android.support.design.widget.FloatingActionButton fab;
    Unbinder unbinder1;
    // 拍照的照片的存储位置
    private String mTempPhotoPath;
    // 照片所在的Uri地址
    private Uri imageUri;

    //调用照相机返回图片文件
    private Uri imageCropUri;
    AlertDialog alertDialog;
    private AppSharedPreferences mSp;
    private int pageNum = 1;
    private List<BabyDynamicMsgEntity.ListBean> dynamicList = new ArrayList<>();
    private ADA_BabyDynamicMsgList adapter;
    private AlertDialog bindRelativeDialog;
    private ADA_SelectRelation mAdapter;
    private CurrentBabyInfoEntity currentBabyInfoEntity;
    private AlertDialog inviteDialog;
    private String currentBabyId;

    @Override
    protected void onFirstUserVisible() {
        Log.e(TAG, "onFirstUserVisible: ");
    }

    @Override
    protected void onUserVisible() {
        Log.e(TAG, "onUserVisible: ");
        //跟随activity生命周期，相当于resume
        if (currentBabyId != null && !currentBabyId.equals(Constants.BABYID)) {
            pageNum = 1;
            mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID);
        }
        if (mPresenter.isLogin()) {
            if (pageNum == 1)
                mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID);

        } else {
            recordBabyheadRiv.setImageDrawable(getResources().getDrawable(R.drawable.healthdata_icon_headportrait_default));
            recordBabybirthTv.setText("");
            recordBabynameTv.setText(getString(R.string.record_unlogin));
            unLogin();
        }
    }

    @Override
    protected void onUserInvisible() {
        Log.e(TAG, "onUserInvisible: ");
    }

    @Override
    protected View getLoadingTargetView() {
        return babyDynamicRv;
    }

    @Override
    protected void initViewsAndEvents() {
//        ((AppCompatActivity)getActivity()).setSupportActionBar(myt);
        int statusBarHeight = ScreenUtil.getStatusBarHeight(mContext);
        myt.setPadding(0, statusBarHeight, 0, myt.getPaddingBottom());
        mSp = new AppSharedPreferences(getActivity());
        adapter = new ADA_BabyDynamicMsgList(getActivity(), dynamicList, mPresenter);
        babyDynamicRv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        babyDynamicRv.setAdapter(adapter);
        babyDynamicRv.setLoadingMoreProgressStyle(ProgressStyle.BallClipRotate);
        babyDynamicRv.setLoadingListener(this);
        babyDynamicRv.setFootViewText("正在努力加载……", "没有更多啦！");
        if (mPresenter.isLogin()) {
            mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID);
        } else {
            unLogin();
        }
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPhotosPermission();
            }
        });
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fra_record;
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {

    }

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void showToast(String msg) {
        CommonUtils.makeEventToast(getActivity(), msg, false);
    }

    @Override
    public void onCurrentBabyReceived(CurrentBabyInfoEntity babyInfoEntity) {
        if (babyInfoEntity == null) {
            mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, "");
            return;
        }
        currentBabyInfoEntity = babyInfoEntity;
        recordBabynameTv.setText(babyInfoEntity.getName());
        recordBabybirthTv.setText(babyInfoEntity.getBirthday());
        Glide.with(this).load(babyInfoEntity.getImageUrl()).error(getResources().getDrawable(R.drawable.healthdata_icon_headportrait_default)).into(recordBabyheadRiv);
        mSp.putString(Constants.BABY_ID, babyInfoEntity.getBabyId());
        Constants.BABYID = babyInfoEntity.getBabyId();
        mPresenter.getBabyDynamicMsgs(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID, "10", Integer.toString(pageNum));
        recordModifyIv.setVisibility(View.VISIBLE);
        if (babyInfoEntity.isFlag()) {
            initBindRelativeDialog();
            mPresenter.getRelationList();
        }
        Constants.RELATIONSHIP = babyInfoEntity.getCreatorId();
        Constants.BABYNAME = babyInfoEntity.getName();
        Constants.BABYBIRTHDAY = DateUtils.formatDateToLong(babyInfoEntity.getDate(), "yyyy-MM-dd");
        currentBabyId = Constants.BABYID;

    }

    @Override
    public void onCurrentBabyNotFound() {
        // 没有宝宝， 显示添加宝宝页面
        Log.e(TAG, "onCurrentBabyNotFound: 1");
        dynamicList.clear();
        BabyDynamicMsgEntity.ListBean listBean = new BabyDynamicMsgEntity.ListBean();
        listBean.setRecordType(Constants.NOCONTENT);
        recordFloatingMenu.setVisibility(View.GONE);
        fab.setVisibility(View.GONE);
        recordBabynameTv.setText("未添加宝宝");
        dynamicList.add(listBean);
        adapter.notifyDataSetChanged();
        recordModifyIv.setVisibility(View.GONE);
        setPullToRefreshEnable(false);
        Log.e(TAG, "onCurrentBabyNotFound: 2");

    }

    private void unLogin() {
        BabyDynamicMsgEntity.ListBean listBean = new BabyDynamicMsgEntity.ListBean();
        listBean.setRecordType(Constants.UNLOGIN);
        dynamicList.clear();
        dynamicList.add(listBean);
        setPullToRefreshEnable(false);
        adapter.notifyDataSetChanged();
        recordFloatingMenu.setVisibility(View.GONE);
        fab.setVisibility(View.GONE);
        recordModifyIv.setVisibility(View.GONE);

    }

    private void setPullToRefreshEnable(boolean isEnable) {
        babyDynamicRv.setPullRefreshEnabled(isEnable);
        babyDynamicRv.setLoadingMoreEnabled(isEnable);
    }

    @Override
    public void onBabyMsgsReceived(BabyDynamicMsgEntity babyDynamicMsgEntity) {
        if (pageNum == 1) {
            babyDynamicRv.refreshComplete();
            BabyDynamicMsgEntity.ListBean headBean = new BabyDynamicMsgEntity.ListBean();
            headBean.setRecordType(Constants.HEADER_ADDPIC);
            headBean.setDate(DateUtils.getWeek(System.currentTimeMillis()));
            dynamicList.clear();
            dynamicList.add(headBean);
//            recordFloatingMenu.setVisibility(View.VISIBLE);
            fab.setVisibility(View.VISIBLE);
            setPullToRefreshEnable(true);
        }
        dynamicList.addAll(babyDynamicMsgEntity.getList());
        babyDynamicRv.loadMoreComplete();
        if (dynamicList.size() - 1 >= babyDynamicMsgEntity.getTotalPage()) {
            babyDynamicRv.setNoMore(true);
        }
        adapter.notifyDataSetChanged();

    }

    @Override
    public void showDeleteConfirmDialog(final String dataId, final int position) {
        alertDialog = new AlertDialog.Builder(getActivity())
                .setContentView(R.layout.dialog_delete_babydynamic)
                .setWidthAndHeight(UtilDynamicWidth.dip2px(310), UtilDynamicWidth.dip2px(200))
                .setCancelableOntheOutside(true)
                .setOnClickListener(R.id.dialog_delete_cancel, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (alertDialog != null) {
                            alertDialog.dismiss();
                        }
                    }
                })
                .setOnClickListener(R.id.dialog_delete_confirm, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPresenter.deleteBabyDynamicMsg(dataId, 1, position);
                        if (alertDialog != null) {
                            alertDialog.dismiss();
                        }
                    }
                })
                .show();


    }

    @Override
    public void onDeleteSuccess(int position) {
        //根据position 更改数据源，直接刷新页面，更快，免去网络请求
        dynamicList.remove(position - 1);
        babyDynamicRv.notifyItemRemoved(dynamicList, position - 1);
    }

    @Override
    public void showChoosePicDialog() {
        checkPhotosPermission();
        /*if (alertDialog != null) {
            alertDialog.dismiss();
        }
        alertDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_open_camera)
                .fromBottom(true)
                .fullWidth()
                .setOnClickListener(R.id.tv_take_photos, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkCameraPermission();
                    }
                })
                .setOnClickListener(R.id.tv_photo_album, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        checkPhotosPermission();
                    }
                })
                .setOnClickListener(R.id.tv_cancel_camera, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                    }
                })
                .show();*/
    }

    private void checkCameraPermission() {
        if (XXPermissions.isHasPermission(getActivity(), Permission.CAMERA)) {
            takePhoto();
        } else {
            XXPermissions.with(getActivity()).permission(Permission.CAMERA)
                    .request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            takePhoto();
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            showToast("您拒绝了必要权限，无法拍照");
                        }
                    });
        }
    }

    private void checkPhotosPermission() {
        if (XXPermissions.isHasPermission(getActivity(), Permission.CAMERA)) {
            choosePhoto();
        } else {
            XXPermissions.with(getActivity()).permission(Permission.CAMERA)
                    .request(new OnPermission() {
                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            choosePhoto();
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            showToast("您拒绝了必要权限，无法打开相册");
                        }
                    });
        }
    }

    @Override
    public void onUploadSucceed(UploadPhotoEntity entity) {
        if (entity == null) {
            return;
        }
        //把图片路径上传到服务器
        mPresenter.saveDiaryPhoto(Constants.TOKEN, Constants.COMPANYID, entity.getShowImg(), entity.getCompressImg(), Constants.BABYID);
    }

    @Override
    public void onSaveDiarySucceed() {
        //上传成功，刷新界面
        pageNum = 1;
        mPresenter.getBabyDynamicMsgs(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID, "10", Integer.toString(pageNum));
    }

    @Override
    public void bindRelativeSuccess() {
        if (bindRelativeDialog != null) {
            bindRelativeDialog.dismiss();
        }
    }

    @Override
    public void updateRelationList(List<RelationEntity.ListBean> list) {
        mAdapter.updateList(list);
        bindRelativeDialog.show();
    }

    /**
     * 拍照实现方法
     */
    private void takePhoto() {
        //打开相机后，关闭弹出框
        if (alertDialog != null) {
            alertDialog.dismiss();
        }

        // 跳转到系统的拍照界面
        Intent intentToTakePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 指定照片存储位置为sd卡本目录下
        // 这里设置为固定名字 这样就只会只有一张temp图 如果要所有中间图片都保存可以通过时间或者加其他东西设置图片的名称
        // File.separator为系统自带的分隔符 是一个固定的常量
        mTempPhotoPath = Environment.getExternalStorageDirectory() + File.separator + "photo.jpeg";
        // 获取图片所在位置的Uri路径    *****这里为什么这么做参考问题2*****
        /*imageUri = Uri.fromFile(new File(mTempPhotoPath));*/
        imageUri = FileProvider.getUriForFile(getActivity(), "com.egg.provider", new File(mTempPhotoPath));
        //下面这句指定调用相机拍照后的照片存储的路径
        intentToTakePhoto.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intentToTakePhoto, CAMERA_REQUEST_CODE);
    }

    /**
     * 打开相册方法实现
     */
    private void choosePhoto() {
        //选择相册后，关闭弹出框
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
        readyGo(ACT_WriteAndChosePhotos.class);
       /* Intent intentToPickPic = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 如果限制上传到服务器的图片类型时可以直接写如："image/jpeg 、 image/png等的类型" 所有类型则写 "image/*"
        intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intentToPickPic, GALLERY_REQUEST_CODE);*/
    }

    /**
     * 界面回调方法 用于将得到的照片处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case CAMERA_REQUEST_CODE:   //调用相机后返回
                if (resultCode == Activity.RESULT_OK) {
                    upLoad(imageUri);
                }
                break;
            case GALLERY_REQUEST_CODE:    //调用相册后返回
                if (resultCode == Activity.RESULT_OK) {
                    Uri uri = data.getData();
                    upLoad(uri);
//                    cropPhoto(uri);       //裁剪
                }
                break;
            case GO_TO_ZOOM:     //调用剪裁后返回 ， 暂时不裁剪
                String encodedPath = imageCropUri.getEncodedPath();
                Uri uriFromFilePath = UriUtils.getUriFromFilePath(encodedPath);
                upLoad(uriFromFilePath);
                break;
            case GO_SWITCH_BABY:
                if (resultCode == Activity.RESULT_OK) {
                    Constants.BABYID = data.getStringExtra(Constants.BABY_ID);
                    mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID);
                }
                break;

        }

    }

    /**
     * 把图片上传到服务器
     */
    public void upLoad(Uri uri) {
        try {
            mPresenter.upLoadPhoto(UriUtils.getBitmapFormUri(getActivity(), uri, "photo"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @OnClick({R.id.record_babyinfo_ll, R.id.record_growth_diary_ll, R.id.record_health_diary_ll
            , R.id.record_invitehomie_tv, R.id.record_title_babylist_iv, R.id.record_floating_camera,
            R.id.record_floating_photo, R.id.record_babyhead_riv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.record_babyinfo_ll://点击更改宝宝信息
            case R.id.record_babyhead_riv:
                if (!mPresenter.isLogin()) {
                    mPresenter.jumpToLogin();
                } else if ("".equals(Constants.BABYID)) {
                    showToast("请先添加宝宝");
                } else if (currentBabyInfoEntity.isIsAdmin()) {
                    mPresenter.editBabyMsg(currentBabyInfoEntity);
                } else {
                    showToast("您没有修改宝宝信息的权限");
                }
                //点击更改宝宝信息
                break;
            case R.id.record_growth_diary_ll:
                //点击跳转到宝宝成长印记
                if (!mPresenter.isLogin()) {
                    mPresenter.jumpToLogin();
                } else if ("".equals(Constants.BABYID)) {
                    showToast("请先添加宝宝");
                } else {
                    readyGo(ACT_GrowthStamp.class);
                }
                break;
            case R.id.record_health_diary_ll:
                //点击跳转到宝宝成长记录
                if (!mPresenter.isLogin()) {
                    mPresenter.jumpToLogin();
                } else if ("".equals(Constants.BABYID)) {
                    showToast("请先添加宝宝");
                } else {
                    mPresenter.jumpToGrowUpRecord(Constants.BABYID);
                }
                break;
            case R.id.record_invitehomie_tv:
                //点击跳转邀请家人
                if (!mPresenter.isLogin()) {
                    mPresenter.jumpToLogin();
                } else if ("".equals(Constants.BABYID)) {
                    showToast("请先添加宝宝");
                } else if (currentBabyInfoEntity.isIsAdmin()) {
                    initInviteDialog();
                    inviteDialog.show();
                } else {
                    showToast("您不是管理员，没有邀请权限");
                }
                break;
            case R.id.record_title_babylist_iv:
                //点击打开宝宝列表
                if (!mPresenter.isLogin()) {
                    mPresenter.jumpToLogin();
                } else if ("".equals(Constants.BABYID)) {
                    showToast("请先添加宝宝");
                } else {
                    jumpToSwitchBaby();
                }
                break;
            case R.id.record_floating_camera:
                //展开菜单 照相机
                checkCameraPermission();
                break;
            case R.id.record_floating_photo:
                // 展开菜单 选择图片
                checkPhotosPermission();
                break;
        }
    }

    /**
     * 跳转切换宝宝
     */
    private void jumpToSwitchBaby() {
        Intent intent = new Intent(mContext, ACT_SwitchBaby.class);
        startActivityForResult(intent, GO_SWITCH_BABY);
    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        mPresenter.getBabyDynamicMsgs(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID, "10", Integer.toString(pageNum));
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        mPresenter.getBabyDynamicMsgs(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID, "10", Integer.toString(pageNum));
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //当前页面不可见
            Log.e(TAG, "onHiddenChanged: h");
        } else {
            //当前页面可见
            Log.e(TAG, "onHiddenChanged: f");
            //只有当page==1时才可以加载，不然会有脏数据问题
            //1.5部分将内部注释掉了，因为没有推送，获取不到自己被移除家族关系的状态引起脏数据，所以强制每次都获取数据
            if (mPresenter.isLogin()) {
                /*if (!"".equals(Constants.BABYID) && pageNum == 1 && !currentBabyId.equals(Constants.BABYID)) {
                    mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID);
//                mPresenter.getBabyDynamicMsgs(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID, "10", Integer.toString(pageNum));
                } else if (!Constants.BABYID.equals(currentBabyId)) {
                    mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID);
                } else if ("".equals(Constants.BABYID)) {
                    //当已登录，无宝宝，从其他fragment滑动到此，尝试重新拉取首页宝宝信息 1-26
                    mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID);

                }*/
                mPresenter.getCurrentBaby(Constants.TOKEN, Constants.COMPANYID, Constants.BABYID);
            } else {
                unLogin();
            }
        }
    }

    private void initBindRelativeDialog() {
        bindRelativeDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_bind_relative)
                .setCancelableOntheOutside(true)
                .create();
        RecyclerView rvRelativeList = bindRelativeDialog.getView(R.id.rv_relative);
        mAdapter = new ADA_SelectRelation(mContext);
        rvRelativeList.setLayoutManager(new GridLayoutManager(mContext, 3));
        mAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                mPresenter.addRelative(Constants.BABYID,
                        mAdapter.getDataList().get(position).getLabel(),
                        mAdapter.getDataList().get(position).getValue());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        rvRelativeList.setAdapter(mAdapter);
    }

    private void initInviteDialog() {
        inviteDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_invitehomie_without_relationship)
                .setWidthAndHeight(mScreenWidth - DisplayUtil.dip2px(mContext, 20), ViewGroup.LayoutParams.WRAP_CONTENT)
                .setCancelableOntheOutside(true)
                .create();
        Window window = inviteDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        inviteDialog.getView(R.id.iv_wechat).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inviteByWechat(currentBabyInfoEntity.getRelationName(), 0);
                inviteDialog.dismiss();
            }
        });
        inviteDialog.getView(R.id.iv_phone).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ACT_PhoneInvite.startAc(mContext, Constants.BABYID, currentBabyInfoEntity.getName());
                inviteDialog.dismiss();
            }
        });
        inviteDialog.getView(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inviteDialog.dismiss();
            }
        });
    }

    private void inviteByWechat(String relationName, int type) {

        UMWeb web = new UMWeb(String.format("%s?token=%s&companyId=%s&babyId=%s&time=%s&name=%s&imgUrl=%s&relationName=%s",
                API.INVITE_WITHOUT_RELATIONSHIP, Constants.TOKEN, Constants.COMPANYID, currentBabyInfoEntity.getBabyId(), System.currentTimeMillis(),
                currentBabyInfoEntity.getName(), currentBabyInfoEntity.getImageUrl(), relationName));//分享链接
        web.setTitle("宝宝的照片都在这里，快来看看吧!");//标题
        web.setDescription("来婴联通，全家的照片都在这");//描述
        switch (type) {
            case 0:
                //分享到微信
                new ShareAction(getActivity())
                        .setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
                        .withMedia(web)//分享链接
                        .setCallback(new UMShareListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {

                            }

                            @Override
                            public void onResult(SHARE_MEDIA share_media) {
                                showToast("邀请成功");
                            }

                            @Override
                            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                showToast("邀请失败");
                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media) {

                            }
                        })//回调监听器
                        .share();
                break;
            case 1:
                //分享到微信朋友圈
                new ShareAction(getActivity())
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)//传入平台
                        .withMedia(web)//分享链接
                        .setCallback(new UMShareListener() {
                            @Override
                            public void onStart(SHARE_MEDIA share_media) {

                            }

                            @Override
                            public void onResult(SHARE_MEDIA share_media) {
                                showToast("邀请成功");
                            }

                            @Override
                            public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                showToast("邀请失败");
                            }

                            @Override
                            public void onCancel(SHARE_MEDIA share_media) {

                            }
                        })//回调监听器
                        .share();
                break;
        }

    }
}
